package com.aliyun.heiyu.powermaster.server;

import com.aliyun.heiyu.common.util.LogUtils;
import com.aliyun.heiyu.powermaster.proto.GetNodeDataReply;
import com.aliyun.heiyu.powermaster.server.manager.DeviceManagerImpl;
import com.aliyun.heiyu.powermaster.server.manager.StrategyManager;
import com.aliyun.heiyu.powermaster.server.util.Configuration;
import com.aliyun.heiyu.powermaster.server.util.ZkClientUtil;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ZkMonitorInIt {

    private static volatile ZkMonitorInIt instance;

    private static Logger logger = LoggerFactory.getLogger(ZkMonitorInIt.class);

    private static int status;

    public static ZkMonitorInIt getInstance() {
        synchronized (ZkMonitorInIt.class) {
            if (instance == null) {
                instance = new ZkMonitorInIt();
            }
            return instance;
        }
    }

    private ZkMonitorInIt() {
        zkInit();
    }


    public void zkInit() {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                logger.debug("========开始监控zk的状态=========" + System.currentTimeMillis());
                GetNodeDataReply nodeData = ZkClientUtil.getNodeData("/leader");
                String leaderIp = nodeData.getData().split(":")[0];
                logger.debug("===========获取现在的主机ip=========" + LogUtils.vaildlog(leaderIp) );
                if (Configuration.IP.equals(leaderIp) && status == 0) {
                    logger.debug("===========现在的ip为leader，并且从未初始化数据，开始初始化=========");
                    DeviceManagerImpl.getInstance().initCache();
                    StrategyManager.getInstance().initCache();
                    status = 1;
                    logger.debug("===========初始化完成，现在status的值为=========" + status);
                }
            }
        };
        ScheduledExecutorService service = new ScheduledThreadPoolExecutor(1, new BasicThreadFactory.Builder().namingPattern("zk-init-pool-%d").daemon(true).build());
        service.scheduleAtFixedRate(runnable, 60, 30, TimeUnit.SECONDS);

    }


}
